<template>
  <a-card :bordered="false" class="card-area">
    <div>
      <a-form-model :model="searchForm" ref="searchForm">
        <a-row>
          <a-col :span="9">
            <a-form-model-item label='监控项目名称' prop='hawkName' :labelCol="{span: 5}" :wrapperCol="{span: 12, offset: 1}">
              <a-input v-model="searchForm.hawkName" placeholder="请输入监控项目名称" allow-clear/>
            </a-form-model-item>
          </a-col>
          <a-col :span="4" class="btnStyle">
            <a-button type="primary" @click="search">查询</a-button>
            <a-button style="margin-left: 8px" @click="reset">重置</a-button>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <div>
      <a-button type="primary" @click="addItem">新增</a-button>
      <a-button @click="del">删除</a-button>
    </div>
    <div style="margin-top:16px;">
      <a-table :data-source="tableItem.data" :columns="tableItem.columns" :rowKey="(record, index) => {return index}" :row-selection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}" :pagination="false">
        <template slot="operation" slot-scope="text, record">
          <a @click="modifyItem(record)">修改</a>
          <a-popconfirm :title="['是否', record.useEnable ? '停用' : '启用' , '本条监控项目？']" @confirm="() => onOff(record)">
            <a href="javascript:;" @click="onORoff(record.useEnable)">{{record.useEnable ? '停用' : '启用'}}</a>
          </a-popconfirm>
        </template>
      </a-table>
    </div>
    <div class="page-box">
      <a-pagination :total="tableItem.total" :show-total="pagination.showTotal" :page-size="searchForm.pageSize" show-size-changer @change="onChange" @showSizeChange="onShowSizeChange" :page-size-options="pagination.pageSizeOptions"/>
    </div>
    <!-- 新增/修改监控任务 -->
    <a-drawer :title="drawerTitle+'监控任务'" :visible="visible" width=70% :closable='false' :maskClosable="false">
      <a-form-model :model="formItem" ref="formItem" :rules="formItemRules" :labelCol="{span: 3}" :wrapperCol="{span: 18}">
        <a-form-model-item label='任务名称' prop="hawkName">
          <a-input v-model="formItem.hawkName" placeholder="请输入任务名称" allow-clear/>
        </a-form-model-item>
        <a-form-model-item label="启用" prop="useEnable">
          <a-switch v-model="formItem.useEnable" checked-children="开" un-checked-children="关"/>
        </a-form-model-item>
        <a-form-model-item label="采集方式" prop='collectionWay'>
          <a-radio-group default-value="formItem.collectionWay" v-model="formItem.collectionWay">
            <a-radio-button value="0" :disabled='formItem.collectionWay === "1"'>推送</a-radio-button>
            <a-radio-button value="1" :disabled='formItem.collectionWay === "0"'>主动采集</a-radio-button>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label='采集频率' prop="collectionFreq" v-show="formItem.collectionWay === '1'">
          <a-input-number style="width: 100%" placeholder="请输入采集频率" allow-clear v-model="formItem.collectionFreq" :min="0"/>
        </a-form-model-item>
        <a-form-model-item label='采集URL' prop='collectionUrl' v-show="formItem.collectionWay === '1'">
          <a-input placeholder="请输入采集URL" allow-clear v-model="formItem.collectionUrl"/>
        </a-form-model-item>
        <a-form-model-item label='最大缓存时间（秒）' prop='cachePeriod'>
          <a-input-number allow-clear v-model="formItem.cachePeriod" :min="30"/>
        </a-form-model-item>
        <a-form-model-item label='指标列表' prop='indexList'>
          <div>
          <span v-for="(item, index) in formItem.indexList" :key="index">
            <a-space>
              <a-input-group compact>
                <a-select style="width: 10%" placeholder="类型" v-model="item.indexType" :rules="{required: true,message:'请选择指标类型',trigger: 'blur'}">
                  <a-select-option value="0" key="0">普通</a-select-option>
                  <a-select-option value="1" key="1">计算</a-select-option>
                </a-select>
                <a-input style="width: 15%" placeholder="指标名" allow-clear v-model="item.indexName" :rules="{required: true,message:'请输入指标名',trigger: 'blur'}"/>
                <a-input style="width: 15%" placeholder="中文名" allow-clear v-model="item.indexDescription" :rules="{required: true,message:'请输入中文描述',trigger: 'blur'}"/>
                <a-input style="width: 12%" placeholder="单位" allow-clear v-model="item.unit" :rules="{required: true,message:'请输入单位',trigger: 'blur'}"/>
                <a-select style="width: 15%" placeholder="计算方法" v-model="item.algorithm" :rules="{required: true,message:'请选择计算方法',trigger: 'blur'}"
                          :disabled="item.indexType!=='1'" @change="algorithmChange(item)">
                  <a-select-option v-for="alg in algorithmList" :value="alg.value" :key="alg.value">{{alg.label}}</a-select-option>
                </a-select>
                <a-input style="width: 23%" placeholder="参数" allow-clear v-model="item.algParams" :rules="{required: true,message:'请输入参数',trigger: 'blur'}" :disabled="item.indexType!=='1'"/>
                <a-select style="width: 10%" placeholder="图表" v-model="item.show">
                  <a-select-option value="1" key="1">展示</a-select-option>
                  <a-select-option value="0" key="0">隐藏</a-select-option>
                </a-select>
              </a-input-group>
              <a-icon type="minus-circle-o" v-if="formItem.indexList.length !== 1" class="dynamic-delete-button" @click="remove(index)" :key="index"/>
            </a-space>
          </span>
          </div>
        </a-form-model-item>
        <a-form-model-item :wrapperCol="{sm: {span: 18, offset: 3}}">
          <a-button type="dashed" style="width: 100%" @click="addItemList">
            <a-icon type="plus"/>添加指标列表
          </a-button>
        </a-form-model-item>
        <a-divider>展示配置</a-divider>
        <a-form-model-item label="监控展示" prop="showEnable">
          <a-switch v-model="formItem.showEnable" checked-children="开" un-checked-children="关"/>
        </a-form-model-item>
        <a-form-model-item label="分组" prop="showGroupName">
          <a-select v-show="showSelect" v-model="formItem.showGroupName" placeholder="请选择分组" :getPopupContainer='prpupContainer' allow-clear>
            <div slot="dropdownRender" slot-scope="menu">
              <div style="padding: 4px 8px; cursor: pointer;" @mousedown="e => e.preventDefault()" @click="addItem1">
                <a-icon type="plus" />新增分组名称
              </div>
              <a-divider style="margin: 4px 0;" />
              <v-nodes :vnodes="menu" />
            </div>
            <a-select-option v-for="(item, index) in groupList" :key="index" :value='item'>{{item}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="显示顺序" prop="showOrder">
          <a-input-number style="width: 100%" placeholder="请输入显示顺序" allow-clear v-model="formItem.showOrder"/>
        </a-form-model-item>
        <a-form-model-item label="图表形式" prop="showChart">
          <a-select v-model="formItem.showChart" placeholder="请选择图表形式" :getPopupContainer='prpupContainer'>
            <a-select-option v-for="(item, index) in chartList" :key="index" :value='item.value' allow-clear>{{item.label}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label='图表参数' prop="showChartParams">
          <a-textarea v-model="formItem.showChartParams" placeholder="请输入图表参数" allow-clear :rows="4" :maxLength='3000'/>
          <a-icon type="question-circle" class="ic iconStyle" theme="twoTone" two-tone-color="#52c41a" @click="showTips = true"/>
        </a-form-model-item>
      </a-form-model>
      <div class="drawer-bootom-button">
        <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
          <a-button style="margin-right: .8rem">取消</a-button>
        </a-popconfirm>
        <a-button @click="handleSubmit" type="primary" :loading="loading">确定</a-button>
      </div>
    </a-drawer>
    <a-modal title="添加分组名称" :visible="isShow" @ok="handleOk" @cancel="isShow = false" :closable='false' :maskClosable="false">
      <a-input v-model="getGroupName" placeholder="请输入分组名称" allow-clear/>
      <a-input v-model="getGroupOrder" placeholder="请输入分组顺序" allow-clear/>
    </a-modal>
    <a-modal title="图表参数提示" :width='810' v-model="showTips" :footer="null">
      <div style="height:510px;overflow-y: scroll;">
        <div v-for="(item, index) in tipsList" :key="index">
        <a-divider>{{item.name}}图参数示例</a-divider>
        <a-row :gutter="2">
           <a-col span='12'>
             <img :src="item.imgUrl" style="width:100%;">
           </a-col>
           <a-col span='12'>
             <div>
               {{item.objExample}}
             </div>
           </a-col>
        </a-row>
      </div>
      </div>
    </a-modal>
  </a-card>
</template>
<script>
export default {
  data () {
    return {
      searchForm: {
        hawkName: '',
        pageNum: 1,
        pageSize: 10
      },
      tableItem: {
        columns: [
          {
            title: '监控项目ID',
            dataIndex: 'hawkId',
            align: 'center',
            width: 200
          },
          {
            title: '监控项目名称',
            dataIndex: 'hawkName',
            align: 'center'
          },
          {
            title: '监控是否启用',
            dataIndex: 'useEnable',
            align: 'center',
            customRender: (useEnable) => {
              switch (useEnable) {
                case true:
                  return <a-tag color="green">启用</a-tag>
                case false:
                  return <a-tag color="red">停用</a-tag>
                default:
                  return useEnable
              }
            }
          },
          {
            title: '采集方式',
            dataIndex: 'collectionWay',
            align: 'center',
            customRender: (collectionWay) => {
              switch (collectionWay) {
                case '0':
                  return '推送'
                case '1':
                  return '主动采集'
                default:
                  return collectionWay
              }
            }
          },
          {
            title: '分组名称',
            dataIndex: 'showGroupName',
            align: 'center'
          },
          {
            title: '图表类型',
            dataIndex: 'showChart',
            align: 'center',
            customRender: (showChart) => {
              switch (showChart) {
                case '03':
                  return '列表图'
                case '02':
                  return '径向表'
                case '01':
                  return '线性表'
                default:
                  return showChart
              }
            }
          },
          {
            title: '操作',
            dataIndex: 'operation',
            scopedSlots: { customRender: 'operation' },
            align: 'center'
          }
        ],
        data: [],
        total: 0
      },
      selectedRows: [],
      selectedRowKeys: [],
      drawerTitle: '',
      visible: false,
      formItem: {
        hawkId: '',
        hawkName: '',
        useEnable: true,
        collectionWay: '',
        collectionFreq: '',
        collectionUrl: '',
        cachePeriod: 30,
        indexList: [{
          indexType: '',
          indexName: '',
          indexDescription: '',
          unit: '',
          algorithm: '',
          algParams: '',
          show: '0'
        }],
        showEnable: true,
        showGroupName: '',
        showOrder: null,
        showChart: '',
        showChartParams: ''
      },
      formItemRules: {
        hawkName: [
          { required: true, type: 'string', message: '请输入任务名称', trigger: 'blur' }
        ],
        useEnable: [
          { required: true, type: 'boolean', message: '请修改启用状态', trigger: 'change' }
        ],
        collectionWay: [
          { required: true, type: 'string', message: '请选择采集方式', trigger: 'change' }
        ],
        showGroupName: [
          { required: true, type: 'string', message: '请选择分组', trigger: 'change' }
        ],
        showChart: [
          { required: true, type: 'string', message: '请选择图表形式', trigger: 'change' }
        ],
        showChartParams: [
          { required: true, type: 'string', message: '请输入图表参数', trigger: 'blur' }
        ],
        cachePeriod: [
          { required: true, message: '请输入缓存时间', trigger: 'blur' }
        ]
      },
      groupList: [],
      chartList: [
        {
          label: '线性表',
          value: '01'
        },
        {
          label: '径向表',
          value: '02'
        },
        {
          label: '列表图',
          value: '03'
        }
      ],
      loading: false,
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      switchName: '',
      switchStatus: false,
      showSelect: true,
      isShow: false,
      getGroupName: '',
      getGroupOrder: '',
      algorithmList: [],
      showTips: false,
      tipsList: [
        {
          name: '折线-单线',
          imgUrl: 'static/img/chartsTips/danXian.png',
          objExample: '{"chart":{"toolbar":{"show":false},"zoom": {"enabled":false}},"dataLabels":{"enabled":false},"stroke": {"curve":"straight"},"title":{},"grid":{"row":{"colors": ["#f3f3f3","transparent"],"opacity": 0.5}},"xaxis": {"categories":[]}}'
        },
        {
          name: '折线-多线',
          imgUrl: 'static/img/chartsTips/duoXian.png',
          objExample: '{"chart":{"toolbar":{"show":false},"zoom": {"enabled":false}},"dataLabels":{"enabled":false},"stroke": {"curve":"straight"},"title":{},"grid":{"row":{"colors": ["#f3f3f3","transparent"],"opacity": 0.5}},"xaxis": {"categories":[]}}'
        },
        {
          name: '径向-基本',
          imgUrl: 'static/img/chartsTips/jxtJiBen.png',
          objExample: '{"chart":{"toolbar":{"show":false}},"plotOptions":{"radialBar":{"dataLabels":{"name":{"fontSize":"22px"},"value":{"fontSize":"16px"},"total":{"show": true}}}},"legend":{"show":true,"floating":true,"fontSize":"16px","position":"left","offsetX":160,"offsetY":15}}'
        },
        {
          name: '径向-多条',
          imgUrl: 'static/img/chartsTips/jxtDuoTiao.png',
          objExample: '{"chart":{"toolbar":{"show":false}},"plotOptions":{"radialBar":{"dataLabels":{"name":{"fontSize":"22px"},"value":{"fontSize":"16px"},"total":{"show": true}}}},"legend":{"show":true,"floating":true,"fontSize":"16px","position":"left","offsetX":160,"offsetY":15}}'
        },
        {
          name: '统计数值',
          imgUrl: 'static/img/chartsTips/tjszImg.png',
          objExample: '{"precision": 2,"decimalSeparator":".","groupSeparator":",","suffix":"%","prefix":"↑","valueStyle":{"color":"red"}}'
        }
      ]
    }
  },
  components: {
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes
    }
  },
  methods: {
    prpupContainer (triggerNode) {
      return triggerNode.parentNode || document.body
    },
    search () {
      this.$get('hawk/config', this.searchForm).then(res => {
        this.tableItem.total = res.data.total
        this.tableItem.data = res.data.rows
      })
    },
    reset () {
      this.$refs.searchForm.resetFields()
      this.searchForm.pageNum = 1
      this.searchForm.pageSize = 10
      this.search()
    },
    onChange (pageNum) {
      this.searchForm.pageNum = pageNum
      this.search()
    },
    onShowSizeChange (current, pageSize) {
      this.searchForm.pageNum = 1
      this.searchForm.pageSize = pageSize
      this.search()
    },
    getList () {
      this.$get('hawk/config/groupList').then(res => {
        this.groupList = res.data
      })
    },
    addItem () {
      this.visible = true
      this.drawerTitle = '新增'
      this.formItem = {
        hawkId: '',
        hawkName: '',
        useEnable: true,
        collectionWay: '',
        collectionFreq: '',
        collectionUrl: '',
        cachePeriod: 30,
        indexList: [
          {
            indexType: '',
            indexName: '',
            indexDescription: '',
            unit: '',
            algorithm: '',
            algParams: '',
            show: '0'
          }
        ],
        showEnable: true,
        showGroupName: '',
        showOrder: null,
        showChart: '',
        showChartParams: ''
      }
      this.showSelect = true
      this.getList()
    },
    addItem1 () {
      this.isShow = true
      this.getGroupName = ''
      this.getGroupOrder = ''
    },
    handleOk () {
      if (this.getGroupName !== '') {
        this.groupList.push((this.getGroupOrder === '' ? '99' : this.getGroupOrder) + '-' + this.getGroupName)
        this.isShow = false
      } else {
        this.$message.warning('分组名称不能为空！')
      }
    },
    del () {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请选择需要删除的记录')
      } else {
        let arr = []
        this.selectedRows.forEach(item => {
          arr.push(item.hawkId)
        })
        this.$delete('hawk/config/delete', {ids: arr}).then(res => {
          if (res.data.status === true) {
            this.$message.success(res.data.message)
            this.selectedRowKeys = []
            this.search()
          } else {
            this.$message.error(res.data.message)
          }
        })
      }
    },
    onORoff (obj) {
      if (obj === true) {
        this.switchStatus = false
      } else {
        this.switchStatus = true
      }
    },
    onOff (obj) {
      let params = {
        id: obj.hawkId,
        useEnable: this.switchStatus
      }
      this.$put('hawk/config/useEnable', params).then(res => {
        if (res.data.status === true) {
          this.$message.success(res.data.message)
          this.search()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    modifyItem (obj) {
      this.visible = true
      this.drawerTitle = '修改'
      this.formItem = {
        hawkId: obj.hawkId,
        hawkName: obj.hawkName,
        useEnable: obj.useEnable,
        collectionWay: obj.collectionWay,
        collectionFreq: obj.collectionFreq,
        collectionUrl: obj.collectionFreq,
        cachePeriod: obj.cachePeriod,
        indexList: obj.indexList,
        showEnable: obj.showEnable,
        showGroupName: obj.showGroupName,
        showOrder: obj.showOrder,
        showChart: obj.showChart,
        showChartParams: obj.showChartParams
      }
      this.showSelect = true
      this.getList()
    },
    onClose () {
      this.search()
      this.visible = false
      this.$refs.formItem.resetFields()
    },
    handleSubmit () {
      this.$refs.formItem.validate(valid => {
        if (valid) {
          let params = {
            hawkMonitorConfigString: JSON.stringify(this.formItem)
          }
          if (this.drawerTitle === '新增') {
            this.$post('hawk/config/add', params).then(res => {
              if (res.data.status === true) {
                this.onClose()
                this.$message.success(res.data.message)
                this.search()
              } else {
                this.$message.error(res.data.message)
              }
            })
          } else if (this.drawerTitle === '修改') {
            this.$put('hawk/config/update', params).then(res => {
              if (res.data.status === true) {
                this.visible = false
                this.$message.success(res.data.message)
                this.search()
              } else {
                this.$message.error(res.data.message)
              }
            })
          }
        } else {
          this.$message.error('表单内容验证失败!')
        }
      })
    },
    addItemList () {
      this.formItem.indexList.push({
        indexType: '0',
        indexName: '',
        indexDescription: '',
        unit: '',
        algorithm: '',
        algParams: '',
        show: '0'
      })
    },
    remove (index) {
      this.formItem.indexList.splice(index, 1)
    },
    getAlgorithmList () {
      this.$get('hawk/config/algorithmList').then(res => {
        this.algorithmList = []
        for (let key in res.data) {
          this.algorithmList.push({
            value: key,
            label: res.data[key]
          })
        }
      })
    },
    algorithmChange (item) {
      if (item.algorithm !== undefined) {
        this.$get('hawk/config/algorithmParamsSample', {algorithm: item.algorithm}).then(res => {
          item.algParams = JSON.stringify(res.data)
        })
      }
    }
  },
  mounted () {
    this.search()
    this.getAlgorithmList()
  }
}
</script>
<style lang='less' scoped>
  .dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 5px;
  right: 0px;
  font-size: 24px;
  color: #999;
}
.page-box {
  text-align: right;
  margin-top:16px;
}
.ic {
  position: relative;
  bottom: 110px;
  left: 101%;
}
</style>
